﻿using Application.Common.Interfaces;
using FluentValidation;
using Microsoft.EntityFrameworkCore;

namespace Application.Features.Users.Commands.Update;

public class AssignRoleToUserCommandValidator : AbstractValidator<AssignRoleToUserCommand>
{
    private readonly IApplicationDbContext _context;
    public AssignRoleToUserCommandValidator(IApplicationDbContext context)
    {
        _context = context;

        RuleFor(v => v.UserIds)
             .MustAsync(BeValidUserAsync!).WithMessage($"非法修改！");
    }

    /// <summary>
    /// 校验用户
    /// </summary>
    /// <param name="command">修改参数</param>
    /// <param name="userIds">用户唯一标识</param>
    /// <param name="cancellationToken">取消标记</param>
    /// <returns>返回布尔值</returns>
    private async Task<bool> BeValidUserAsync(AssignRoleToUserCommand command, List<long> userIds, CancellationToken cancellationToken)
    {
        var users = await _context.Users.Where(x => userIds.Contains(x.Id)).ToListAsync();
        if (!users.Any()) return false;

        var isSystemAccount = users.Any(x => x.IsSystemAccount == true);

        if (isSystemAccount)
            return false;

        return true;
    }
}